/**
 * 检测学号是否合法
 */
function checkStuNum(){
	
	var r=$('#reporterId').val();
	var p =/[^\d]/;
	var d=r.replace(p,"");
	$('#reporterId').val(d);
}
/**
 * 检测电话格式
 */
function checkPhoneNum(){
	var r=$('#reporterPhoneNum').val();
	var p =/[^\d-]/;
	var d=r.replace(p,"");
	$('#reporterPhoneNum').val(d);
}

/**
 * 时间对象的格式化
 */
Date.prototype.format = function(format) {
	/*
	 * format="yyyy-MM-dd hh:mm:ss";
	 */
	var o = {
		"M+" : this.getMonth() + 1,
		"d+" : this.getDate(),
		"h+" : this.getHours(),
		"m+" : this.getMinutes(),
		"s+" : this.getSeconds(),
		"q+" : Math.floor((this.getMonth() + 3) / 3),
		"S" : this.getMilliseconds()
	}

	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}

	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}
//随机产生
function _getRandomString(len) {  
    len = len || 32;  
    var $chars = 'abcdefhijkmnprstwxyz'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1  
    var maxPos = $chars.length;  
    var pwd = '';  
    for (i = 0; i < len; i++) {  
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));  
    }  
    return pwd;  
}  

//产生事件号ID
function createEventId(){
	var time = new Date();
	return time.format("yyyyMMddhhmm")+_getRandomString(8);
}

// 保存事件处理
function saveEvent() {
	if($('#eventForm').form('validate')){
		ajaxLoading('保存事件中...');
		$('#eventForm').form('submit', {
			url : 'Event_add',
			onSubmit : function() {
				// alert($('#eventForm').serialize());
				return $(this).form('validate');
			},
			success : function(data) {
				var obj = eval('(' + data + ')');
				closeMsg(0);
				if (!obj.RESULT) {
					showMsg("保存事件失败", 0);
				} else {
					showMsg("保存事件成功", 1);
				}
			}
		});
	}
}

// 发送邮件给报导人
function sendEmail() {
		if($('#eventForm').form('validate')){
				ajaxLoading("邮件发送中...");
				$('#eventForm').form('submit', {
					url : 'Mail',
					success : function(data) {
						closeMsg(0);
						var obj = eval('(' + data + ')');
						if (!obj.RESULT) {
							showMsg("发送邮件失败，请重试", 0);
						} else {
							showMsg("发送邮件成功", 1);
						}
					}
				});
		}
}

// 发送短信初始化
function sendSMS() {
	
	if($('#department').val()==''){
		showMsg('请先选择主管部门',0);
	}else if($('#username').val()==''){
		showMsg('请先选择部门领导',0);
	}else{
		$('#fm').form('load', {
			"name" : $('#username1').val(),
			"addr" : $('#phone').val(),
			"text" :$('#mainContent').val()
		});
		$('#sendSMS').dialog('open');
	}
}

// 发送短信操作
function doSendSMS() {
	if ($('#fm').form('validate')) {
		ajaxLoading("正在发送中...");
		$('#sendSMS').dialog('close');
		$.ajax({
			url : 'Sms',
			type : 'POST',
			data:$('#fm').serialize(),
			success : function(data) {
				if (!data.RESULT) {
					closeMsg(1);
					$.messager.alert("操作提示",
							"<font size=\"4\">短信发送失败，请重试</font>", "error",
							function() {
								$('#sendSMS').dialog('open');
							});
				} else {
					closeMsg(1);
					showMsg("发送短信成功", 1);
				}
			},
			error : function() {
				closeMsg(1);
				$.messager.alert("操作提示", "<font size=\"4\">短信发送失败，请重试</font>",
						"error", function() {
							$('#sendSMS').dialog('open');
						});
			}
		});
	}
}

$(function() {
	//初始化事件日期
	$('#nowDate').attr('value',new Date().format("yyyy-MM-dd"));
	//初始化事件ID号
	var eventId=createEventId();
	$('#eventId3').attr('value',eventId);
	$('#eventId2').attr('value',eventId);
	$('#eventId1').html(eventId);
	$('#eventId').attr('value',eventId);
	// 刷新班级下拉框值
	var json;
	var json1;
	$.ajax({
		url : 'Resource_classList',
		type : 'GET',
		dataType : 'json',
		success : function(data) {
			json = data;
			alert(JSON.stringify(json));
			var str = '<option></option>';
			$.each(data, function(i, n) {
				str = str + "<option value=" + n.CLASSID + ">" + n.CLASSNAME
						+ "</option>";
			});
			$('#classRoom').html(str);
		}
	});

	// 刷新主管部门下拉框
	$.ajax({
		url : 'Resource_departmentList',
		type : 'GET',
		dataType : 'json',
		success : function(data) {
			json1 = data;
			var str = '<option></option>';
			$.each(data,
					function(i, n) {
						str = str + "<option title=" + n.USERDESCRIPTION
								+ " value=" + n.DEPARTMENTID + ">"
								+ n.DEPARTMENTNAME + "</option>";
					});
			$('#department').html(str);
		}
	});

	// 班级下拉框改变，班主任与辅导员相应显示
	$('#classRoom').change(function() {
		var i = this.selectedIndex - 1;
		if (i >= 0) {
			$("#Monitor").attr("value", json[i].CLASSMONITORNAME);
			$('#Director').attr("value", json[i].CLASSDIRECTORNAME);
			$('#reporterDepartment').attr("value", json[i].CLASSDEPARTMENTID);
		} else {
			$("#Monitor").attr("value", "");
			$('#Director').attr("value", "");
		}
	});
	
	var json2;
	//主管部门
	$('#department').change(function() {
		$.get('Resource_leaderList?departmentId='+$('#department').val(),function(json){
			json2=json;
			var str = '<option></option>';
			$.each(json,
					function(i, n) {
						str = str + "<option title=" + n.USERDESCRIPTION
								+ " value=" + n.USERID + ">"
								+ n.USERNAME + "</option>";
					});
			$('#username').html(str);
			//清空手机号码
			$('#phone').attr("value", "");
		},'json');
	});
	
	
	//部门领导
	$('#username').change(function(){
		var i = this.selectedIndex - 1;
	if (i >= 0) {
		$('#phone').attr("value", json2[i].PHONE);
		$('#DirectorMail').attr("value", json2[i].MAIL);
		$('#username1').attr("value", json2[i].USERNAME);
	} else {
		$('#phone').attr("value", "");
	}
	});
});

//============================检测是否为音频或者图片=====================
function checkIsImage(){
	var t = /\.(jpg|jpeg|png)$/;
	var img = $('#imageFile').val();
	if(img==''){
		showMsg('请选择图片上传',0);
		return false;
	}
	if(!t.test(img)){
		showMsg('您选择的不是图片，请选择图片(jpg,jpeg,png)',0);
		return false;
	}
	return true;
}

function checkIsAudio(){
	var t = /\.(mp3|wav)$/;
	var audio = $('#audioFile').val();
	if(audio==''){
		showMsg('请选择录音上传',0);
		return false;
	}
	if(!t.test(audio)){
		showMsg('您选择的不是录音，请选择录音(mp3,wav)',0);
		return false;
	}
	return true;
}
//===========================结束==============================

//根据是否支持浏览器 显示不同的播放器
function checkPlayer(){
		 if (window.applicationCache) {
	         return true;
	     } else {
	         return false;
	     }
}

//播放录音
function audioPlayer(eId,aId){
	if(checkPlayer()){
		//html5播放器
		$('#statrAudio').html("<audio src=\"Audio_get?eventId="+eId+"&&id="+aId+"\" controls=\"controls\"></audio><iframe id=\"tmp_downloadhelper_iframe\" style=\"display: none;\"></iframe>");
	}else{
		//微软播放器
		$('#statrAudio').html("<embed src=\"Audio_get?eventId="+eId+"&&id="+aId+"\" height=\"50px\" width=\"300px\"pluginspage=\"http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=media&sba=plugin&\" type=\"application/x-mplayer2\" border=\"0\" width=\"100%\" height=\"40\" showcontrols=\"1\" showaudiocontrols=\"1\" showstatusbar=\"1\" autostart=\"0\" loop=\"0\" enablecontextmenu=\"1\"></embed>");
	}
	$('#audioPlayer').dialog('open');
}

//刷新图片页面
function reloadImage(eId){
	$.get("Image_exist?eventId="+eId,function(json){
		var str='';
		if(json!=null){
			$.each(json,function(i,n){
				str = str + "<a target=\"_Blank\"href=\"Image_get?eventId="+eId+"&&id="+n.IMAGEID+"\" title=\"点击查看图片\">"+n.IMAGENAME+"</a><a onclick=\"deleteImage('"+eId+"','"+n.IMAGEID+"')\"><img title=\"点击删除\" src=\"images/delete.gif\"></a>";
			});
			$('#imageBox').html(str);
		}
	},'json');
}

//刷新录音列表
function reloadAudio(eId){
	$.get("Audio_exist?eventId="+eId,function(json){
		var str='';
		if(json!=null){
			$.each(json,function(i,n){
				str = str + "<a onclick=\"audioPlayer('"+eId+"','"+n.AUDIOID+"')\" title=\"点击播放录音\">"+n.AUDIONAME+"</a><a onclick=\"deleteAudio('"+eId+"','"+n.AUDIOID+"')\"><img title=\"点击删除\" src=\"images/delete.gif\"></a>";
			});
			$('#audioBox').html(str);
		}
	},'json');
}

//上传录音
function uploadAudio(){
	if(checkIsAudio()){
		$('#uploadAudioLoading').html("<img src=\"images/upload.gif\" width=\"100\" height=\"15\"/>");
	$('#audioForm').form('submit',{
		url : 'Audio_add',
		success : function(data) {
			var obj = eval('(' + data + ')');
			if (!obj.RESULT) {
				$('#uploadAudioLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>上传失败！</font>");
			} else {
				$('#uploadAudioLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>上传成功！</font>");
				reloadAudio($('#eventId2').val());
			}
			setTimeout(function(){
				$('#uploadAudioLoading').html('');
			},3000);
		}
	});
	}
};

//上传图片
function uploadImage(){
	if(checkIsImage()){
		$('#uploadImageLoading').html("<img src=\"images/upload.gif\" width=\"100\" height=\"15\"/>");
		$('#imageForm').form('submit',{
		url : 'Image_add',
		success : function(data) {
			var obj = eval('(' + data + ')');
			if (!obj.RESULT) {
				$('#uploadImageLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>上传失败！</font>");
			} else {
				$('#uploadImageLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>上传成功！</font>");
				reloadImage($('#eventId3').val());
			}
			setTimeout(function(){
				$('#uploadImageLoading').html('');
			},3000);
		}
	});
	}
}

//删除图片
function deleteImage(eid,imgId){
	$.messager.confirm('友情提示', '您确定要删除吗?',function(data){
		if(data){
			$.ajax({
				url:'Image_delete',
				type:'GET',
				data:'id='+imgId+'&&eventId='+eid,
				dataType:'json',
				beforeSend:function(){
					$('#uploadImageLoading').html("<img src=\"images/deleteLoading.gif\"/>&nbsp;<font color=red>删除中...</font>");
				},
				success:function(json){
					if(json.RESULT){
						$('#uploadImageLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>删除成功！</font>");
						reloadImage($('#eventId2').val());
					}else{
						$('#uploadImageLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					}
					setTimeout(function(){
						$('#uploadImageLoading').html('');
					},3000);
				},
				error:function(){
					$('#uploadImageLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					setTimeout(function(){
						$('#uploadImageLoading').html('');
					},3000);
				}
			});
		}
	})
}

//删除录音
function deleteAudio(eid,aId){
	$.messager.confirm('友情提示', '您确定要删除吗?',function(data){
		if(data){
			$.ajax({
				url:'Audio_delete',
				type:'GET',
				data:'id='+aId+'&&eventId='+eid,
				dataType:'json',
				beforeSend:function(){
					$('#uploadAudioLoading').html("<img src=\"images/deleteLoading.gif\"/>&nbsp;<font color=red>删除中...</font>");
				},
				success:function(json){
					if(json.RESULT){
						$('#uploadAudioLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>删除成功！</font>");
						reloadAudio($('#eventId2').val());
					}else{
						$('#uploadAudioLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					}
					setTimeout(function(){
						$('#uploadAudioLoading').html('');
					},3000);
				},
				error:function(){
					$('#uploadAudioLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					setTimeout(function(){
						$('#uploadAudioLoading').html('');
					},3000);
				}
			});
		}
	})
}

//打印事件
function printEvent(){
	if($('#eventForm').form('validate')){
		$.messager.confirm('友情提示', '您真的要打印吗？',function(data){
			if(data){
				window.open("Event_print?"+$('#eventForm').serialize());
			}
		});
	}else{
		showMsg("打印之前，先填写完整事件基本内容",0);
	}
}

//防止session过期初始化
window.onload=function(){
	window.setInterval('avoidSessionExpire()',5*60*1000);
}

//防止session过期操作
function avoidSessionExpire(){
	$.get('Login_sessionExpire?rd='+new Date().valueOf(),function(data){
		//不做处理
	},'json');
}